'use strict';
const UniSecObj = require('uni-sec-check')
const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;

module.exports = class ShoppingController extends Controller {
	
	// 开通笔记
	async openNote() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		try {
			// 开通笔记
			response.datas = await this.service.utils.openNoteUser(uid, user);
			response.code = 0;
		} catch(e) {
			response.msg = e.message;
		}
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 添加笔记
	async addNote() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		// 数据验证
		await this.validateNote(this.ctx.data);
		
		const {
			title,
			content,
			goods,
			video,
			imgs
		} = this.ctx.data;
		
		// 添加笔记
		const addRes = await this.db.collection('wmzmall-shopping-note').add({
			note_gid: goods._id || '',
			note_goods: goods,
			note_video: video || {},
			note_imgs: imgs || [],
			note_title: title,
			note_desc: content,
			note_praise: 0,
			note_collect: 0,
			version: 1,
			state: '正常',
			is_delete: 0,
			create_time: Date.now(),
			create_uid: uid,
			create_uname: user.uname,
			create_uheadimg: user.uheadimg
		});
		
		if (addRes.id) {
			// 记录笔记数
			const updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
				notep_note: this.db.command.inc(1)
			});
			if (!updateRes.updated) {
				// 发布后自动开通笔记功能
				await this.service.utils.openNoteUser(uid, user, {
					// 笔记数为 1
					notep_note: 1
				});
			}
			
			response.code = 0;
		}
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	// 验证笔记内容
	async validateNote(req) {
		if (!req) this.throw('请求参数不存在');
		if (!req.title) this.throw('请填写标题');
		if (!req.content) this.throw('请填写正文');
		
		if (!( (req.imgs && req.imgs.length) || (req.video && req.video.url) )) this.throw('请上传视频或图片');
		
		const uCheck = new UniSecObj({
		    provider: 'mp-weixin'
		});
		
		// 文字内容安全检测
		let txtRes = await uCheck.textSecCheck({
			content: req.content + req.title
		});
		uniCloud.logger.info('txtRes', txtRes);
		if (txtRes.errCode) {
			txtRes.type = '文字';
			this.throw(txtRes);
		}
		
		// 图片内容安全检测 
		if (req.imgs) {
			for (var idx = 0; idx < req.imgs.length; idx++) {
				let img = req.imgs[idx];
				
				if (img.url.indexOf('cdn.bspapp.com') !== -1) {
					// 压缩图片大小
					let process = '?x-oss-process=image/resize,p_50/quality,Q_80';
					// 根据图片大小，进行压缩
					if (img.size > 1024*1024*3) {
						process = '?x-oss-process=image/resize,p_10/quality,Q_50';
					} else if (img.size > 1024*1024*2) {
						process = '?x-oss-process=image/resize,p_20/quality,Q_60';
					} else if (img.size > 1024*1024*1) {
						process = '?x-oss-process=image/resize,p_30/quality,Q_70';
					} else if (img.size > 1024*600) {
						process = '?x-oss-process=image/resize,p_40/quality,Q_80';
					}
					img.url += process;
				}
				
				console.log('img.url ' + idx, img.url);
				
				let imgRes = await uCheck.imgSecCheck({
					image: img.url
				});
				uniCloud.logger.info('imgRes', imgRes);
				if (imgRes.errCode) {
					imgRes.idx = idx;
					imgRes.type = '图片';
					this.throw(imgRes);
				}
			}
		}
	}
	
	
	// 列表
	async list() {
		let response = {
			code: 1,
		};
		
		const start = Date.now();
		const nowdate = start;
		let {
			uid		// 用户的笔记，不存在代表列表页查询
		} = this.ctx.data;
		
		const {
			tid,
			val
		} = this.ctx.data;
		
		// 查询笔记
		let noteRes = await this.noteDatas(this.ctx.data);
		
		if (noteRes.data && noteRes.data.length > 0 && !uid) {
			if (this.ctx.event.uniIdToken) {
				// 已登录，获取当前登录 uid
				const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
				if (user.code == 0) {
					uid = user.uid;
					
					// 我的点赞
					const likesRes = await this.db.collection('wmzmall-shopping-user').doc(uid).field({ notep_likes: true, notep_collect: true }).get();
					const [notep = {}] = likesRes.data;
					// 已点赞数据
					if (notep.notep_likes && notep.notep_likes.length > 0) {
						noteRes.data.forEach(x => {
							if (notep.notep_likes.find(n => n == x._id)) {
								x.likes = true;
							}
						});
					}
					// 已收藏数据
					if (notep.notep_collect && notep.notep_collect.length > 0) {
						noteRes.data.forEach(x => {
							if (notep.notep_collect.find(n => n == x._id)) {
								x.collect = true;
							}
						});
					}
				}
			}
		}
		
		if (tid == '全部' && !val) {
			// 第一次请求
			const paramRes = await this.db.collection('wmzmall-shopping-parameter').where({
				is_delete: 0
			}).get();
			response.param = paramRes.data[0] || {};
			if (response.param && response.param._id && response.param.ad) {
				const ads = response.param.ad;
				delete response.param.ad;
				response.param.ads = [];
				ads.forEach(x => {
					if (x.start_time < nowdate && x.end_time >= nowdate && x.state) {
						response.param.ads.push(x);
					}
				});
			}
		}
		response.datas = noteRes.data;
		response.code = 0;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	// 笔记数据
	async noteDatas(res) {
		let {
			uid,	// 用户的笔记
			tid,	// 全部|关注|其他代表分类ID
			rows, 	// 每页数据条数
			ids,	// 过滤已存在数据ID
			val,	// 最后一条数据值
			islikes,		// 点赞
			iscollect,		// 收藏
			keyword			// 关键词
		} = res;
		
		let whereObj = { };
		if (ids && ids.length > 0) {
			whereObj._id = this.db.command.nin(ids);
		}
		
		whereObj.is_delete = 0;
		whereObj.state = '正常';
		
		if (uid) {
			// 点赞、收藏
			if (islikes == 1) {
				const likesRes = await this.db.collection('wmzmall-shopping-user').doc(uid).field({ notep_likes: true }).get();
				if (likesRes.data && likesRes.data.length) {
					ids = likesRes.data[0].notep_likes;
				}
				
				rows = ids.length;
				// uid 点赞的数据
				whereObj._id = this.db.command.in(ids);
			} else if (iscollect == 1) {
				const collectRes = await this.db.collection('wmzmall-shopping-user').doc(uid).field({ notep_collect: true }).get();
				if (collectRes.data && collectRes.data.length) {
					ids = collectRes.data[0].notep_collect;
				}
				
				rows = ids.length;
				// uid 收藏的数据
				whereObj._id = this.db.command.in(ids);
			} else {
				// 查看用户笔记
				whereObj.create_uid = uid;
			}
		}
		
		if (tid == '全部') {
			
		} else if (tid == '关注') {
			// todo
			
		} else if (tid) {
			// 分类ID
			whereObj.note_goods = {};
			whereObj.note_goods.cids = tid;
		}
		
		// 创建时间降序
		let field = 'create_time';
		let sort = 'desc';
			
		// 用于分页筛选，查询小于等于最后时间的数据
		if (val) whereObj.create_time = this.db.command.lte(val);
		
		// 搜索标题
		if (keyword) whereObj.note_title = new RegExp(keyword);
		
		console.log('noteDatas whereObj', whereObj);
		
		let dbctx = this.db.collection('wmzmall-shopping-note')
			.where(whereObj)
			.orderBy(field, sort);
		
		const noteRes = await dbctx
			.limit(rows || 6)
			.get();
		
		return noteRes;
	}
	
	// 详情
	async detail() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		const {
			id
		} = this.ctx.data;
		
		// 验证ID有效性
		const note = await this.getNote(id);
		note.follow = false;
		note.likes = false;
		note.collect = false;
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
				
				// 我的关注、点赞、收藏
				const noteUserRes = await this.db.collection('wmzmall-shopping-user').doc(uid).field({ notep_attention: true, notep_likes: true, notep_collect: true }).get();
				const [notep = {}] = noteUserRes.data;
				response.notep = notep;
				// 已关注数据
				if (notep.notep_attention && notep.notep_attention.length) {
					if (notep.notep_attention.find(n => n == note.create_uid)) {
						note.follow = true;
					}
				}
				// 已点赞数据
				if (notep.notep_likes && notep.notep_likes.length) {
					if (notep.notep_likes.find(n => n == note._id)) {
						note.likes = true;
					}
				}
				// 已收藏数据
				if (notep.notep_collect && notep.notep_collect.length) {
					if (notep.notep_collect.find(n => n == note._id)) {
						note.collect = true;
					}
				}
			}
		}
		
		response.code = 0;
		response.datas = note;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 用户
	async user() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		const {
			id
		} = this.ctx.data;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;

		
		// 验证ID有效性
		const noteUser = await this.getNoteUser(id || uid, true);
		
		// 当前登录者ID
		noteUser.iself = noteUser.user._id === uid;
		response.code = 0;
		response.datas = noteUser;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	// 我的关注
	async myFollow() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		const {
			id
		} = this.ctx.data;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		
		// 验证ID有效性
		const noteUser = await this.getNoteUser(id || uid, true);
		// 我的关注
		const followDatas = await this.db.collection('wmzmall-shopping-user').where({
			_id: this.db.command.in(noteUser.notep_attention)
		}).field({
			notep_name: true,
			notep_headimg: true
		}).get();
		
		// 当前登录者ID
		response.iself = noteUser.user._id === uid;
		response.code = 0;
		response.datas = followDatas.data;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	// 我的粉丝
	async myFans() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		const {
			id
		} = this.ctx.data;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		
		// 验证ID有效性
		const noteUser = await this.getNoteUser(id || uid, true);
		// 我的粉丝
		const fansDatas = await this.db.collection('wmzmall-shopping-user').where({
			_id: this.db.command.in(noteUser.notep_fans)
		}).field({
			notep_name: true,
			notep_headimg: true
		}).get();
		
		// 当前登录者ID
		response.iself = noteUser.user._id === uid;
		response.code = 0;
		response.datas = fansDatas.data;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 点赞
	async likes() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		const {
			id
		} = this.ctx.data;
		
		// 验证ID有效性
		const note = await this.getNote(id);
		
		// 点赞
		// 记录点赞数据
		const updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
			notep_likes: this.db.command.addToSet(id)
		});
		
		if (updateRes.updated) {
			// 统计笔记被点赞数
			await this.db.collection('wmzmall-shopping-note').doc(note._id).update({
				note_praise: this.db.command.inc(1)
			});
			// 统计笔记人总获赞数
			await this.db.collection('wmzmall-shopping-user').doc(note.create_uid).update({
				notep_praise: this.db.command.inc(1)
			});
		}
		
		response.code = 0;
		response.datas = updateRes;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	// 取消点赞
	async likesCancel() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		const {
			id
		} = this.ctx.data;
		
		// 取消点赞
		const updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
			notep_likes: this.db.command.pull(id)
		});
			
		if (updateRes.updated) {
			try {
				// 验证ID有效性
				const note = await this.getNote(id);
				
				// 统计笔记被点赞数
				await this.db.collection('wmzmall-shopping-note').where({
					_id: note._id,
					note_praise: this.db.command.gte(1)
				}).update({
					note_praise: this.db.command.inc(-1)
				});
				// 统计笔记人总获赞数
				await this.db.collection('wmzmall-shopping-user').where({
					_id: note.create_uid,
					notep_praise: this.db.command.gte(1)
				}).update({
					notep_praise: this.db.command.inc(-1)
				});
			} catch(e) { }
		}
		
		response.code = 0;
		response.datas = updateRes;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 收藏
	async collect() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		const {
			id
		} = this.ctx.data;
		
		// 验证ID有效性
		const note = await this.getNote(id);
		
		// 收藏
		// 记录收藏数据
		const updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
			notep_collect: this.db.command.addToSet(id)
		});
		
		if (updateRes.updated) {
			response.datas.collect = true;
			// 统计笔记被收藏数
			await this.db.collection('wmzmall-shopping-note').doc(note._id).update({
				note_collect: this.db.command.inc(1)
			});
			// 统计笔记人总被收藏数
			await this.db.collection('wmzmall-shopping-user').doc(note.create_uid).update({
				notep_by_collect: this.db.command.inc(1)
			});
		}
		
		response.code = 0;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	// 取消收藏
	async collectCancel() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		const {
			id
		} = this.ctx.data;
		
		// 取消收藏
		const updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
			notep_collect: this.db.command.pull(id)
		});
			
		if (updateRes.updated) {
			response.datas.collect = false;
			try {
				// 验证ID有效性
				const note = await this.getNote(id);
				
				// 统计笔记被收藏数
				await this.db.collection('wmzmall-shopping-note').where({
					_id: note._id,
					note_collect: this.db.command.gte(1)
				}).update({
					note_collect: this.db.command.inc(-1)
				});	
				// 统计笔记人总被收藏数
				await this.db.collection('wmzmall-shopping-user').where({
					_id: note.create_uid,
					notep_by_collect: this.db.command.gte(1)
				}).update({
					notep_by_collect: this.db.command.inc(-1)
				});
			} catch(e) { }
		}
		
		response.code = 0;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 关注
	async follow() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		const {
			id		// 用户ID
		} = this.ctx.data;
		
		if (uid == id) {
			response.code = 100;
			response.msg = '不能关注自己';
			return response;
		}
		
		// 验证ID有效性
		const noteUser = await this.getNoteUser(id);
		
		let updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
			notep_attention: this.db.command.addToSet(noteUser._id)
		});
		if (updateRes.updated) {
			// 关注成功
			// 成为他的粉丝
			await this.db.collection('wmzmall-shopping-user').doc(noteUser._id).update({
				notep_fans: this.db.command.addToSet(uid)
			});
			response.datas.follow = true;
		} else {
			// 取消关注
			updateRes = await this.db.collection('wmzmall-shopping-user').doc(uid).update({
				notep_attention: this.db.command.pull(noteUser._id)
			});
			
			if (updateRes.updated) {
				// 取消关注成功
				// 退出粉丝
				await this.db.collection('wmzmall-shopping-user').doc(noteUser._id).update({
					notep_fans: this.db.command.pull(uid)
				});
				response.datas.follow = false;
			}
		}
		
		response.code = 0;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 删除笔记
	async del() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		}
		
		const start = Date.now();
		const nowdate = start;
		
		// 当前登录用户数据
		const user = await this.service.utils.getUser(this.ctx.event.uniIdToken);
		const uid = user.uid;
		
		const {
			id
		} = this.ctx.data;
		
		// 验证ID有效性
		const note = await this.getNote(id);
		
		if (note.create_uid !== uid) {
			response.msg = `仅支持删除自己的笔记`;
			return response;
		}
		
		// 删除笔记数据
		const updateRes = await this.db.collection('wmzmall-shopping-note').doc(id).update({
			is_delete: 1
		});

		if (updateRes.updated) {
			// 统计笔记人笔记数
			await this.db.collection('wmzmall-shopping-user').where({
				_id: uid,
				notep_note: this.db.command.gte(1)
			}).update({
				notep_note: this.db.command.inc(-1)
			});
		}
		
		response.code = 0;
		response.datas = updateRes;
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.duration = `耗时：${end - start}ms`;
		
		return response;
	}
	
	// 获取笔记数据
	async getNote(id) {
		const noteRes = await this.db.collection('wmzmall-shopping-note').doc(id).get();
		const [note] = noteRes.data;
		
		if (!(note && note._id)) {
			this.throw('笔记不存在');
		}
		
		if (note.is_delete !== 0) {
			this.throw('笔记已删除');
		}
		
		if (note.state !== '正常') {
			this.throw('笔记已违规');
		}
		
		return note;
	}
	// 获取笔记用户数据
	async getNoteUser(id, isUserData = false) {
		const noteUserRes = await this.db.collection('wmzmall-shopping-user').doc(id).get();
		const [noteUser] = noteUserRes.data;
		
		if (!(noteUser && noteUser._id) || noteUser.is_delete == 1) {
			this.throw('笔友不存在');
		}
		
		if (isUserData) {
			const userRes = await this.db.collection('wmzmall-member').doc(noteUser._id).field({
				slogan: true,
				member_headimg: true,
				member_nickname: true,
				member_name: true,
				member_city: true
			}).get();
			
			noteUser.user = userRes.data[0]; 
		}
		
		return noteUser;
	}

}
